/*
 * Copyright (c) ycq_work@163.com
 */

package com.mxg.blog.controller.articleAdmin;

import com.mxg.blog.common.CqLogger;
import com.mxg.blog.common.ResultCode;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ycq_work@163.com
 * @DATE: 2023/5/27 6:01
 * 修改头像
 */
@Controller
public class UploadAvatar {
    CqLogger logger = CqLogger.getInstance();

    @PostMapping("api/uploadAvatar")
    public ResponseEntity<Map<String, Object>> coverUpload(@RequestParam("file") MultipartFile file){
        Map<String, Object> resultMap = new HashMap<>();

        logger.print("上传头像");

        if(file.isEmpty())
        {
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_UPLOAD_ERROR);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_UPLOAD_ERROR);
            return ResponseEntity.ok(resultMap);
        }
        else if(!file.isEmpty()){
            try{
                // 获取文件保存的临时文件夹
                String savePath = "E:/javaImageDemo/";
                // 如果目录不存在，则创建目录
                File saveDir = new File(savePath);
                if (!saveDir.exists()) {
                    saveDir.mkdirs();
                }

                // 保存上传的文件到指定的目录中
                String fileName = file.getOriginalFilename();
                File saveFile = new File(saveDir, fileName);
                file.transferTo(saveFile);
                // 获取上传成功后的文件 URL，并封装为 JSON 对象返回
                String fileUrl = /*"http://localhost:8081/" +*/ savePath + fileName;
                logger.print(fileUrl);
                resultMap.put(ResultCode.code, ResultCode.SUCCESS_CODE);
                resultMap.put(ResultCode.message, ResultCode.SUCCESS_MESSAGE);
                resultMap.put(ResultCode.url, fileUrl);
                return ResponseEntity.ok(resultMap);
            }catch (IOException e) {
                // 发生异常时返回包含错误信息的 JSON 对象
                Map<String, String> result = new HashMap<>();
                resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_UPLOAD_ERROR);
                result.put(ResultCode.message, "上传失败" + e.getMessage());
                return ResponseEntity.ok(resultMap);
            }
        }
        return ResponseEntity.ok(resultMap);
    }

}
